package cn.zime.iot.handler;

import cn.zime.iot.entity.AdminDO;
import cn.zime.iot.service.AdminService;
import cn.zime.iot.service.impl.AdminServiceImpl;
import cn.zime.iot.view.FindPassword;
import cn.zime.iot.view.LoginView;
import cn.zime.iot.view.MainView;
import cn.zime.iot.view.RegisterAccountView;

import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;


public class LoginHandler extends KeyAdapter implements ActionListener {

    private final LoginView loginView;

    public LoginHandler(LoginView loginView) {
        this.loginView = loginView;
    }

    @Override
    public void actionPerformed(ActionEvent e) {
        JButton jButton = (JButton) e.getSource();
        String text = jButton.getText();
        if ("取消".equals(text)) {
            loginView.dispose();
        } else if ("登录".equals(text)) {
            login();
        } else if ("注册账号".equals(text)) {
            System.out.println("注册");
            new RegisterAccountView();
        } else if ("找回密码".equals(text)) {
            System.out.println("找回");
            new FindPassword();
        }
    }

    private void login() {
        String user = loginView.getUserTxt().getText();
        char[] chars = loginView.getPwdField().getPassword();
        if (user == null || "".equals(user.trim()) ||
                chars == null) {
            JOptionPane.showMessageDialog(loginView, "用户名密码必填");
            return;
        }
        String pwd = new String(chars);
        System.out.println(user + ":" + pwd);
        //查询DB
        AdminService adminService = new AdminServiceImpl();
        AdminDO adminDO = new AdminDO();
        adminDO.setUserName(user);
        adminDO.setPwd(pwd);
        boolean flag = adminService.validateAdmin(adminDO);
        if (flag) {
            MainView mainView=new MainView();
            mainView.setUserName(user);
            loginView.dispose();//销毁登陆界面
        } else {
            JOptionPane.showMessageDialog(loginView, "用户名密码错误");
        }
    }


    @Override
    public void keyPressed(KeyEvent e) {
        if (KeyEvent.VK_ENTER == e.getKeyCode()) {
            login();
        }
    }
}
